<template>
  <div>
    <h3>走向/输送</h3>
    <div class="table-body">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row style="margin-bottom: 20px;" :gutter="20">
            <el-col :span="13">
              <sportChangesportItem ref="sport2sportItem" search="search" :showPlayer="true" :sportChangesportItemData="sportChangesportItemData"
                @selectDataChange='searchSelectDataChange' title="教练员" playerTitle="被输送人"/>
            </el-col>
            <el-col :span="3">
              <el-select v-model="searchForm.towardId" style="margin-left: 20px;width: 80%;" size="small" collapse-tags
                filterable clearable placeholder="选择走向">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_towar" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.trSportId" @change="trSportChange" style="margin-left: 20px;" size="small" filterable clearabl placeholder="选择输送前运动项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.trSportItemId" size="small" filterable clearable placeholder="选择输送前运动小项">
                <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in trSportItemData" :key="index">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="5" style="display: flex;">
              <el-button type="success" icon="el-icon-plus" size="medium" @click="insertEvent">新增</el-button>
              <el-button type="success" icon="el-icon-printer" size="medium" @click="exportData">导出</el-button>
              <el-button type="success" icon="el-icon-printer" size="medium" @click="printEvent">打印</el-button>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.allSportId" @change="allSportChange" size="small" filterable clearable placeholder="选择吸收项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_allSport" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.allSportItemId" size="small" filterable clearable placeholder="选择吸收小项">
                <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in allSportItemData" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="right" unlink-panels style="width: 80%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="3" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="3">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="800" stripe highlight-hover-row highlight-current-row
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="player" title="被输送人" sortable></vxe-table-column>
        <vxe-table-column field="coach" title="在训教练" sortable></vxe-table-column>
        <vxe-table-column field="inOrg" title="接受单位" sortable></vxe-table-column>
        <vxe-table-column field="towar" title="走向" sortable></vxe-table-column>
        <vxe-table-column field="sportDate" title="训练开始时间" sortable></vxe-table-column>
        <vxe-table-column field="transportDate" title="输送时间" sortable></vxe-table-column>
        <vxe-table-column field="outOrg" title="输出单位名称" sortable></vxe-table-column>
        <vxe-table-column field="trSport" title="输送前运动项目" sortable></vxe-table-column>
        <vxe-table-column field="trSportItem" title="输送前运动小项" sortable></vxe-table-column>
        <vxe-table-column field="allSport" title="吸收项目" sortable></vxe-table-column>
        <vxe-table-column field="allSportItem" title="吸收小项" sortable></vxe-table-column>
        <vxe-table-column field="coachName" title="教练员" sortable></vxe-table-column>
        <vxe-table-column field="memo" title="备注" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="150">
          <template #default="{ row,rowIndex }">
            <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
            <el-button @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle></el-button>
            <el-tooltip class="item" effect="dark" content="复制此条记录为新增模板" placement="top">
              <el-button @click="copyEvent(row)" type="primary" size="medium" icon="el-icon-tickets" circle></el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
        <vxe-table-column field="createUser" title="录入人" sortable></vxe-table-column>
        <vxe-table-column field="checkUser" title="审核人" sortable>
          <template #default="{ row }">
            <span v-if="row.checkUserId!=0">{{row.checkUser}}</span>
            <el-link v-else @click="checkedEvent(row)" type="success">{{row.checkUser}}</el-link>
          </template>
        </vxe-table-column>
        <vxe-table-column field="fileName" title="文件" sortable width="150">
          <template #default="{ row }">
            <div v-loading="row.downloadShow">
              <el-upload
                class="upload-demo"
                action="/match/fileUpload"
                :on-change="beforeFileUpload"
                :limit="1"
                :auto-upload="false"
                :show-file-list="false"
                :file-list="fileList">
                <el-button @click="clickFileUpload(row)" size="medium" type="primary">选择文件</el-button>
              </el-upload>
              <div v-show="row.fileName">
                <el-link @click="downloadFile(row)" type="success">下载-{{row.fileName}}</el-link>
              </div>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="insertModal" title="走向/输送" height="80%" width="500">
      <template #default>
        <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="110px">
          <el-form-item label="运动项目" prop="sportId">
            <el-select v-model="insertForm.sportId" @change="sportChange" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运动小项" prop="sportItemId">
            <el-select v-model="insertForm.sportItemId" @change="sportItemChange" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in sportItemData" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="被输送人" prop="playerId">
            <el-select v-model="insertForm.playerId" filterable clearable style="width: 80%;" placeholder="请选择" @change="playerChange">
              <el-option :label="item.name+' '+$moment(item.birthday).format('YYYY-MM-DD')+' '+(dict_coach[item.coachId]||'')" :value="item.playerId" v-for="(item,index) in playerData" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="接收单位" prop="inOrgId">
            <el-select v-model="insertForm.inOrgId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_allOrg" :key="index"></el-option>
            </el-select>
            <el-link v-if="!inOrgInsertShow" @click="inOrgInsertShow=true" style="font-size: 80%;" icon="el-icon-plus" type="success">未找到需要的机构？点击该行新增 <i class="el-icon-plus el-icon--right"></i> </el-link>
            <el-input v-else style="margin-top: 10px;" placeholder="请输入接收单位" v-model="allOrg" class="input-with-select">
              <el-button @click="allOrgInsert" slot="append" icon="iconfont icon-save"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="走向" prop="towardId">
            <el-select v-model="insertForm.towardId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_towar" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="训练开始时间" prop="sportDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.sportDate" style="width: 80%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="输送时间" prop="transportDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.transportDate" style="width: 80%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="输出单位名称" prop="outOrgId">
            <el-select v-model="insertForm.outOrgId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_allOrg" :key="index"></el-option>
            </el-select>
            <el-link v-if="!outOrgInsertShow" @click="outOrgInsertShow=true" style="font-size: 80%;" icon="el-icon-plus" type="success">未找到需要的机构？点击该行新增 <i class="el-icon-plus el-icon--right"></i> </el-link>
            <el-input v-else style="margin-top: 10px;" placeholder="请输入输出单位" v-model="allOrg" class="input-with-select">
              <el-button @click="allOrgInsert" slot="append" icon="iconfont icon-save"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="输送前运动项目" prop="trSportId">
            <el-select v-model="insertForm.trSportId" @change="trSportChange" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="输送前运动小项" prop="trSportItemId">
            <el-select v-model="insertForm.trSportItemId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in trSportItemData" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="吸收项目" prop="allSportId">
            <el-select v-model="insertForm.allSportId" @change="allSportChange" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_allSport" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="吸收小项" prop="allSportItemId">
            <el-select v-model="insertForm.allSportItemId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in allSportItemData" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教练员" prop="coachName">
            <el-input v-model="insertForm.coachName" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="insertForm.memo" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
  import {
    player_transport,
    player_transport_insert,
    player_transport_update,
    player_transport_check,
    player_transport_delete,
    transport_fileUpload,
    transport_filePath4pdf,
    sport_item_by_sportId,
    pcm4player,
    all_org_insert,
    fileDownload_transmission
  } from '@/api/person.js'
  import {
    userId2EmpName,
    coachByOrgIgnoreRole,
    sport_by_org,
    sport_item,
    all_org,
    toward,
    get_sport,
    currentRolePlayer
  } from '@/api/dict.js'
  import sportChangesportItem from '@/components/sport2sportItem/sport2sportItem.vue'
  export default {
    components: {
      sportChangesportItem
    },
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        dict_sport: {},
        dict_sportItem: {},
        dict_player: {},
        dict_coach: {},
        dict_allOrg: {},
        dict_towar: {},
        dict_allSport: {},
        dict_allSportItem: {},
        dict_userId2empName: {},
        dict_createUser: {},
        dict_checkUser: {},
        insertForm: {
          sportId: '',
          sportItemId: '',
          playerId: '',
          inOrgId: '',
          towardId: '',
          sportDate: '',
          transportDate: '',
          outOrgId: '',
          trSportId: '',
          trSportItemId: '',
          allSportId: '',
          allSportItemId: '',
          coachName: '',
          memo: '',
        },
        searchForm: {
          sportId: '',
          sportItemId: '',
          playerId: '',
          coachId: '',
          towardId: '',
          trSportId: '',
          trSportItemId: '',
          allSportId: '',
          allSportItemId: '',
        },
        playerData: [],
        sportItemData: [],
        trSportItemData: [],
        allSportItemData: [],
        rules: {
          playerId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          sportDate: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          transportDate: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
        },
        isInsert: true,
        transportId: '',
        pid: '',
        sportChangesportItemData: {},
        fileList: [],
        allOrg: '',
        inOrgInsertShow: false,
        outOrgInsertShow: false,
        dict_joinDate: {},
        dict_leftDate: {},
        search: false,
        currentIndex: null,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.player_transport()
      })
    },
    computed: {
      openDateValid() {
        if (this.insertForm.openDate && this.insertForm.closeDate) {
          if (this.insertForm.openDate > this.insertForm.closeDate) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      }
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      copyEvent(row) {
        this.insertForm.playerId = row.playerId==0?'':row.playerId+''
        this.insertForm.inOrgId = row.inOrgId==0?'':row.inOrgId+''
        this.insertForm.towardId = row.towardId==0?'':row.towardId+''
        this.insertForm.sportDate = row.sportDate
        this.insertForm.transportDate = row.transportDate
        this.insertForm.outOrgId = row.outOrgId==0?'':row.outOrgId+''
        this.insertForm.trSportId = row.trSportId==0?'':row.trSportId+''
        this.trSportChange()
        this.insertForm.trSportItemId = row.trSportItemId==0?'':row.trSportItemId+''
        this.insertForm.allSportId = row.allSportId==0?'':row.allSportId+''
        this.allSportChange()
        this.insertForm.allSportItemId = row.allSportItemId==0?'':row.allSportItemId+''
        this.insertForm.coachName = row.coachName
        this.insertForm.memo = row.memo
        this.insertForm.createUserId = row.createUserId
        this.insertForm.checkUserId = row.checkUserId
        this.insertForm.fileName = row.fileName
        this.isInsert = true
        this.insertModal = true
      },
      playerChange(val) {
        this.insertForm.sportDate = this.dict_joinDate[val]
        this.insertForm.transportDate = this.dict_leftDate[val]
      },
      allOrgInsert(){
        all_org_insert({name:this.allOrg}).then(res=>{
          if(res.code === 200) {
            this.$message.success('添加成功')
            all_org().then(res => {
              this.dict_allOrg = res
            })
          }else{
            this.$message.error(res.message)
          }
          if(this.inOrgInsertShow){
            this.inOrgInsertShow = false
          }else if(this.outOrgInsertShow){
            this.outOrgInsertShow = false
          }else{
            this.inOrgInsertShow = false
            this.outOrgInsertShow = false
          }
          this.allOrg = ''
        })
      },
      sport2player() {
        let data = {}
        if(this.insertForm.sportId) data.sportId = this.insertForm.sportId
        if(this.insertForm.sportItemId) data.sportItemId = this.insertForm.sportItemId
        pcm4player(data).then(res=>{
          this.playerData = res.data
        })
      },
      sportItemChange(){
        this.insertForm.playerId = ''
        this.sport2player()
      },
      sportChange() {
        this.insertForm.sportItemId = ''
        this.insertForm.playerId = ''
        sport_item_by_sportId({
          sportId: this.insertForm.sportId
        }).then(res => {
          if (res.code === 200) {
            this.sportItemData = res.data
            this.sport2player()
          }
        })
      },
      trSportChange() {
        this.insertForm.trSportItemId = ''
        sport_item_by_sportId({
          sportId: this.insertForm.trSportId
        }).then(res => {
          if (res.code === 200) {
            this.trSportItemData = res.data
          }
        })
      },
      allSportChange() {
        this.insertForm.allSportItemId = ''
        sport_item_by_sportId({
          sportId: this.insertForm.allSportId
        }).then(res => {
          if (res.code === 200) {
            this.allSportItemData = res.data
          }
        })
      },
      downloadFile(row){
        row.downloadShow = true
        this.$forceUpdate()
        fileDownload_transmission(row.transportId).then(res=>{
           try {
              var blob = res.data;
             // FileReader主要用于将文件内容读入内存
              var reader = new FileReader();
              reader.readAsDataURL(blob);
              // onload当读取操作成功完成时调用
              reader.onload = function(e) {
                var a = document.createElement('a');
                // 获取文件名fileName
                var fileName = res.headers["content-disposition"].split("=");
                fileName = fileName[fileName.length - 1];
                fileName = fileName.replace(/"/g, "");
                fileName = decodeURI(fileName)
                a.download = fileName;
                a.href = e.target.result;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
              }
            }catch{
               this.$message.warning('没有找到文件！')
            }
            row.downloadShow = false
            this.$forceUpdate()
        })
      },
      beforeFileUpload(file){
        this.fileRow.downloadShow = true
        if (file.size > 1024 * 1024 * 100) {
          this.fileRow.downloadShow = false
          this.$message.error('上传文件太大!不能超过100M');
          return
        }
        let fileName = encodeURI(file.name)
        let fileData = new FormData()
        fileData.append("fileName",this.fileRow.transportId+"-"+ fileName);
        fileData.append("file", file.raw);
        transport_fileUpload(fileData).then(res=>{
          if(res.code === 200) {
            this.fileRow.fileName = this.fileRow.transportId+"-"+ file.name
            this.fileRow.downloadShow = false
            this.$message.success('上传成功!')
          }else{
            this.$message.error('上传失败!')
            this.fileRow.downloadShow = false
          }
        })
      },
      clickFileUpload(row){
        this.fileRow = row
      },
      searchSelectDataChange({
        sportId,
        sportItemId,
        person,
        playerId
      }) {
        this.searchForm.sportId = sportId
        this.searchForm.sportItemId = sportItemId
        this.searchForm.coachId = person
        this.searchForm.playerId = playerId
      },
      insertSelectDataChange({
        sportId,
        sportItemId,
        person,
        playerId
      }) {
        this.insertForm.sportId = sportId
        this.insertForm.sportItemId = sportItemId
        this.insertForm.playerId = playerId
        this.insertForm.coachId = person
      },
      clearTableFilter() {
        this.searchForm = {
          sportId: '',
          sportItemId: '',
          playerId: '',
          coachId: '',
          towardId: '',
          trSportId: '',
          trSportItemId: '',
          allSportId: '',
          allSportItemId: '',
        }
        this.doubleDate = ''
        this.sportChangesportItemData = {}
        this.$refs.sport2sportItem.personChange()
        this.player_transport()
      },
      searchSubmit() {
        let data = {}
        if (this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if (this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if (this.searchForm.playerId) data.playerId = this.searchForm.playerId
        if (this.searchForm.coachId) data.coachId = this.searchForm.coachId
        if (this.searchForm.towardId) data.towardId = this.searchForm.towardId
        if (this.searchForm.trSportId) data.trSportId = this.searchForm.trSportId
        if (this.searchForm.trSportItemId) data.trSportItemId = this.searchForm.trSportItemId
        if (this.searchForm.allSportId) data.allSportId = this.searchForm.allSportId
        if (this.searchForm.allSportItemId) data.allSportItemId = this.searchForm.allSportItemId
        if (this.doubleDate) {
          data.startDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        player_transport(data).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          player_transport_delete({
            transportId: row.transportId,playerId:row.playerId
          }).then(res => {
            if (res.code === 200) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.transportId == row.transportId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      checkedEvent(row) {
        this.$confirm('注意：审核过之后，该条数据将不能再被修改', '审核', {
          confirmButtonText: '√通过审核',
          cancelButtonText: '放弃审核',
          type: 'warning'
        }).then(() => {
          player_transport_check({
            transportId: row.transportId
          }).then(res => {
            if (res.code === 200) {
              this.player_transport()
              this.$message.success('已审核.！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消审核.'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        if (row.checkUserId!=0) {
          this.$message.warning('已经审核过的数据不能修改')
        } else {
          this.transportId = row.transportId
          this.insertForm.playerId = row.playerId==0?'':row.playerId+''
          this.insertForm.inOrgId = row.inOrgId==0?'':row.inOrgId+''
          this.insertForm.towardId = row.towardId==0?'':row.towardId+''
          this.insertForm.sportDate = row.sportDate
          this.insertForm.transportDate = row.transportDate
          this.insertForm.outOrgId = row.outOrgId==0?'':row.outOrgId+''
          this.insertForm.trSportId = row.trSportId==0?'':row.trSportId+''
          this.trSportChange()
          this.insertForm.trSportItemId = row.trSportItemId==0?'':row.trSportItemId+''
          this.insertForm.allSportId = row.allSportId==0?'':row.allSportId+''
          this.allSportChange()
          this.insertForm.allSportItemId = row.allSportItemId==0?'':row.allSportItemId+''
          this.insertForm.coachName = row.coachName
          this.insertForm.memo = row.memo
          this.insertForm.createUserId = row.createUserId
          this.insertForm.checkUserId = row.checkUserId
          this.insertForm.fileName = row.fileName
          this.isInsert = false
          this.insertModal = true
        }
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if (this.insertForm.playerId) data.playerId = this.insertForm.playerId
            if (this.insertForm.inOrgId) data.inOrgId = this.insertForm.inOrgId
            if (this.insertForm.towardId) data.towardId = this.insertForm.towardId
            if (this.insertForm.sportDate) data.sportDate = this.$moment(this.insertForm.sportDate).format(
              'YYYY-MM-DD') + ' 00:00:00'
            if (this.insertForm.transportDate) data.transportDate = this.$moment(this.insertForm.transportDate)
              .format('YYYY-MM-DD') + ' 00:00:00'
            if (this.insertForm.outOrgId) data.outOrgId = this.insertForm.outOrgId
            if (this.insertForm.trSportId) data.trSportId = this.insertForm.trSportId
            if (this.insertForm.trSportItemId) data.trSportItemId = this.insertForm.trSportItemId
            if (this.insertForm.allSportId) data.allSportId = this.insertForm.allSportId
            if (this.insertForm.allSportItemId) data.allSportItemId = this.insertForm.allSportItemId
            if (this.insertForm.coachName) data.coachName = this.insertForm.coachName
            if (this.insertForm.memo) data.memo = this.insertForm.memo
            if (this.isInsert) {
              player_transport_insert(data).then(res => {
                if (res.code === 200) {
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            } else {
              data.transportId = this.transportId
              player_transport_update(data).then(res => {
                if (res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.transportId==item.transportId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.isInsert = true
        this.insertModal = true
      },
      exportData() {
        this.$refs.XTable.exportData({
          filename: this.$store.state.user.org+'运动员'+this.$route.meta.title, type: 'csv',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEvent() {
        let topHtml = '<h2>走向/输送</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '走向/输送',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      player_transport() {
        this.loading = true
        player_transport().then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item => {
          item.player = this.dict_player[item.playerId]
          item.coach = this.dict_coach[item.coachId]
          item.inOrg = this.dict_allOrg[item.inOrgId]
          item.towar = this.dict_towar[item.towardId]
          item.sportDate = this.$moment(item.sportDate).format('YYYY-MM-DD') == 'Invalid date' ? '' :
            this.$moment(item.sportDate).format('YYYY-MM-DD')
          item.transportDate = this.$moment(item.transportDate).format('YYYY-MM-DD') ==
            'Invalid date' ? '' : this.$moment(item.transportDate).format('YYYY-MM-DD')
          item.outOrg = this.dict_allOrg[item.outOrgId]
          item.trSport = this.dict_sport[item.trSportId]
          item.trSportItem = this.dict_sportItem[item.trSportItemId]
          item.allSport = this.dict_allSport[item.allSportId]
          item.allSportItem = this.dict_sportItem[item.allSportItemId]
          item.createUser = this.dict_userId2empName[item.createUserId]
          if (item.checkUserId) {
            item.checkUser = this.dict_userId2empName[item.checkUserId]
          } else {
            item.checkUser = '未审核'
          }
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data.reverse()
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          coachByOrgIgnoreRole().then(res => {
            this.dict_coach = res
          }).then(() => {
            sport_by_org().then(res => {
              this.dict_sport = res
            })
          }).then(() => {
            sport_item().then(res => {
              this.dict_sportItem = res
            })
          }).then(() => {
            all_org().then(res => {
              this.dict_allOrg = res
            })
          }).then(() => {
            toward().then(res => {
                this.dict_towar = res
            })
          }).then(() => {
            get_sport().then(res => {
                this.dict_allSport = res
            })
          }).then(()=>{
            userId2EmpName().then(res => {
              this.dict_userId2empName = res
            }).then(()=>{
              currentRolePlayer(true).then(res => {
                this.playerData = res
                res.forEach(item=>{
                  this.dict_player[item.playerId] = item.name
                  this.dict_joinDate[item.playerId] = item.joinDate
                  this.dict_leftDate[item.playerId] = item.leftDate
                })
                resolve()
               })
            })
          })
        })
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[0])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
